﻿using Learun.Util;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using static Learun.Application.TwoDevelopment.ZZDT_EC.ProjectSugar;
using static Learun.Util.SqlSugar.SqlSugarHelper;

namespace Learun.Application.TwoDevelopment.ZZDT_EC
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2022-06-21 15:33
    /// 描 述：工程数据关联表
    /// </summary>
    public class ec_enginedata_relBLL : ec_enginedata_relIBLL
    {
        private ec_enginedata_relService ec_enginedata_relService = new ec_enginedata_relService();

        #region 获取数据
        /// <summary>
        /// 根据句柄来的
        /// </summary>
        /// <param name="CablePixelID"></param>
        /// <param name="ProjectId"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public CableConnRes GetCableConn(CableConnRel CablePixelID, string ProjectId)
        {            //serv
            var pixelServ = new ec_enginedata_pixelService();
            var RelTypeServ = new ec_reltypeService();

            //根据句柄和图纸，先把工程id查出来先
            var drawingID = CablePixelID.DrawingID;
            var pixelID = CablePixelID.CablePixelID;
            var EngineDataIDs = pixelServ.GetList("{\"ProjectId\":\"" + ProjectId + "\",\"PixelCode\":\"" + pixelID + "\",\"DrawingFileID\":\"" + drawingID + "\"}").
                                                    Select(x => x.EngineDataID).Distinct();
            if (EngineDataIDs != null && EngineDataIDs.Count() == 1)
            {
                var CableID = EngineDataIDs.First();
                var End1 = "";
                var End2 = "";
                //查单一记录
                var existRel = this.GetList("{ProjectId:\"" + ProjectId + "\",RelType:\"" + (int)enum_RelType.设备_电缆 + "\",RelEngineDataID:\"" + CableID + "\"}");
                if (existRel.Count(x => x.RelEngineData1ID == CableID) == 1) // 电缆在end1，代表该行记录的end2 是 设备
                {
                    End2 = existRel.Where(x => x.RelEngineData1ID == CableID).Select(x => x.RelEngineData2ID).FirstOrDefault();
                }
                if (existRel.Count(x => x.RelEngineData2ID == CableID) == 1) // 电缆在end2，代表该行记录的end1 是 设备
                {
                    End1 = existRel.Where(x => x.RelEngineData2ID == CableID).Select(x => x.RelEngineData1ID).FirstOrDefault();
                }
                return new CableConnRes
                {
                    CableID = CableID,
                    End1 = End1,
                    End2 = End2
                };
            }
            else
            {
                throw new Exception($"根据句柄{pixelID}查询出的ec_enginedata_pixel有多个ID记录。");
            }
        }



        /// <summary>
        /// 根据工程ID来的
        /// </summary>
        /// <param name="CablePixelID"></param>
        /// <param name="ProjectId"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public CableConnRes GetCableConn(string CableID, string ProjectId)
        {            //serv
            var pixelServ = new ec_enginedata_pixelService();
            var RelTypeServ = new ec_reltypeService();

            var End1 = new ec_enginedata_relEntity();
            var End2 = new ec_enginedata_relEntity();
            //查单一记录
            var existRel = this.GetList("{ProjectId:\"" + ProjectId + "\",RelType:\"" + (int)enum_RelType.设备_电缆 + "\",RelEngineDataID:\"" + CableID + "\"}");
            if (existRel.Count(x => x.RelEngineData1ID == CableID) == 1) // 电缆在end1，代表该行记录的end2 是 设备
            {
                End2 = existRel.Where(x => x.RelEngineData1ID == CableID).FirstOrDefault();
            }
            if (existRel.Count(x => x.RelEngineData2ID == CableID) == 1) // 电缆在end2，代表该行记录的end1 是 设备
            {
                End1 = existRel.Where(x => x.RelEngineData2ID == CableID).FirstOrDefault();
            }
            return new CableConnRes
            {
                CableID = CableID,
                End1Tag = End1.TagNumber1,
                End2Tag = End2.TagNumber2
            };

        }

        /// <summary>
        /// 获取列表数据
        /// <summary>
        /// <returns></returns>
        public IEnumerable<ec_enginedata_relEntity> GetList(string queryJson, Pagination pagination = null)
        {
            try
            {
                var queryParam = queryJson.ToJObject();
                var ProjectId = queryParam["ProjectId"]?.ToString();
                var RelTypeID = queryParam["RelTypeID"]?.ToString();
                var RelTypeIDs = queryParam["RelTypeIDs"]?.ToString();
                var RelEngineDataID = queryParam["RelEngineDataID"]?.ToString();
                var RelEngineData1ID = queryParam["RelEngineData1ID"]?.ToString();
                var RelEngineData2ID = queryParam["RelEngineData2ID"]?.ToString();
                var RelTypeName = queryParam["RelTypeName"]?.ToString();
                var RelType = queryParam["RelType"]?.ToString();
                var TagNumber = queryParam["TagNumber"]?.ToString();

                var tableName = TableName<ec_enginedata_relEntity>(ProjectId);
                var typeTableName = TableName<ec_reltypeEntity>(ProjectId);
                var dataTableName = TableName<ec_enginedataEntity>(ProjectId);

                var query = Db.Queryable<ec_enginedata_relEntity>().AS(tableName)
                    .InnerJoin<ec_reltypeEntity>((a, b) => a.RelTypeID == b.RelTypeID).AS<ec_reltypeEntity>(typeTableName)
                    .WhereIF(!string.IsNullOrEmpty(RelTypeID), a => a.RelTypeID == RelTypeID)
                    .WhereIF(!string.IsNullOrEmpty(RelTypeIDs), a => SqlFunc.SplitIn(RelTypeIDs, a.RelTypeID))
                    .WhereIF(!string.IsNullOrEmpty(RelEngineDataID), a => a.RelEngineData1ID == RelEngineDataID || a.RelEngineData2ID == RelEngineDataID)
                    .WhereIF(!string.IsNullOrEmpty(RelEngineData1ID), a => a.RelEngineData1ID == RelEngineData1ID)
                    .WhereIF(!string.IsNullOrEmpty(RelEngineData2ID), a => a.RelEngineData2ID == RelEngineData2ID)
                    .WhereIF(!string.IsNullOrEmpty(RelTypeName), (a, b) => b.RelTypeName == RelTypeName)
                    .WhereIF(!string.IsNullOrEmpty(RelType), (a, b) => b.RelType == RelType);

                List<ec_enginedata_relEntity> list;
                if (pagination == null)
                {
                    list = query.ToList();
                }
                else
                {
                    list = query.ToPageList(pagination.page, pagination.rows);
                }
                List<string> dataIds = new List<string>();
                list?.ForEach(x =>
                {
                    dataIds.Add(x.RelEngineData1ID);
                    dataIds.Add(x.RelEngineData2ID);
                });
                var types = Db.Queryable<ec_reltypeEntity>().AS(typeTableName).ToList();
                var objectTableName = TableName<ec_objecttypeEntity>(ProjectId);
                var datas = Db.Queryable<ec_enginedataEntity>().AS(dataTableName)
                    .InnerJoin<ec_objecttypeEntity>((a, b) => a.ObjectTypeID == b.ObjectTypeID && dataIds.Contains(a.EngineDataID)).AS<ec_objecttypeEntity>(objectTableName)
                    .Select((a, b) => new
                    {
                        a.EngineDataID,
                        a.TagNumber,
                        b.ObjectTypeName
                    }).ToList();
                list?.ForEach(x =>
                {
                    x.RelTypeName = types.FirstOrDefault(y => y.RelTypeID == x.RelTypeID)?.RelTypeName;
                    x.TagNumber1 = datas.FirstOrDefault(y => y.EngineDataID == x.RelEngineData1ID)?.TagNumber;
                    x.TagNumber2 = datas.FirstOrDefault(y => y.EngineDataID == x.RelEngineData2ID)?.TagNumber;
                    x.Type1 = datas.FirstOrDefault(y => y.EngineDataID == x.RelEngineData1ID)?.ObjectTypeName;
                    x.Type2 = datas.FirstOrDefault(y => y.EngineDataID == x.RelEngineData2ID)?.ObjectTypeName;
                });
                if (!string.IsNullOrEmpty(TagNumber))
                {
                    list = list.Where(x => x.TagNumber1.Contains(TagNumber) || x.TagNumber2.Contains(TagNumber)).ToList();
                }
                return list;
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }
        #endregion

        #region 提交数据

        /// <summary>
        /// 删除实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void DeleteEntity(string ProjectId, string keyValue)
        {
            try
            {
                ec_enginedata_relService.DeleteEntity(ProjectId, keyValue);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }
        /// <summary>
        /// 删除实体数据
        /// <param name="RelTypeId">关系的ID</param>
        /// <param name="ID1">主键1</param>
        /// <param name="ID2">主键2</param>
        /// <summary>
        /// <returns></returns>
        public void DeleteEntity(string ProjectId, string RelTypeId, string ID1, string ID2)
        {
            try
            {
                ec_enginedata_relService.DeleteEntity(ProjectId, RelTypeId, ID1, ID2);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        /// <summary>
        /// 保存实体数据（新增、修改）。
        /// 对应电缆 - 设备（电缆的终止设备，IsEnd2）
        /// <param name="RelEngineData1ID">电缆ID，大概率</param>
        /// <param name="NeedRemove">是否移除已有的，true的话，基本就是确保一对一的这种rel关系</param>
        /// <summary>
        /// <returns></returns>
        public void SaveEntitys(string ProjectId, string RelTypeID, string RelEngineData1ID, List<string> relEngineData2IDs, bool NeedRemove = false)
        {
            try
            {

                //获取当前工程数据ID关联的数据(不管在end1 还是 end2）
                var engineDataRel = GetList("{ProjectId:\"" + ProjectId + "\",RelTypeID:\"" + RelTypeID + "\",RelEngineDataID:\"" + RelEngineData1ID + "\"}").ToList();
                ec_enginedata_relEntity model = new ec_enginedata_relEntity();
                List<ec_enginedata_relEntity> engineDataRelAdd = new List<ec_enginedata_relEntity>();
                //List<ec_enginedata_relEntity> engineDataRelDel = new List<ec_enginedata_relEntity>();
                //List<ec_enginedata_relEntity> engineDataRelExcept = new List<ec_enginedata_relEntity>();//用来比较集合之间的差集
                foreach (var item in relEngineData2IDs)
                {
                    if (NeedRemove)
                    {
                        this.DeleteEntity(ProjectId, RelTypeID, RelEngineData1ID, "");
                        model = new ec_enginedata_relEntity();
                        model.Create();
                        model.RelTypeID = RelTypeID;
                        model.RelEngineData1ID = RelEngineData1ID;
                        model.RelEngineData2ID = item;
                        engineDataRelAdd.Add(model);
                        continue;
                    }
                    else
                    {
                        //先判断位号之间是否有关联关系 关联关系不存在就新增 存在就不用管
                        model = engineDataRel?.Find(x => x.RelEngineData1ID == RelEngineData1ID && x.RelEngineData2ID == item);
                        if (model == null)
                        {
                            model = engineDataRel?.Find(x => x.RelEngineData2ID == RelEngineData1ID && x.RelEngineData1ID == item);
                            //反过来如果连接关系有，那也不会新建
                            if (model == null)
                            {
                                model = new ec_enginedata_relEntity();
                                model.Create();
                                model.RelTypeID = RelTypeID;
                                model.RelEngineData1ID = RelEngineData1ID;
                                model.RelEngineData2ID = item;
                                engineDataRelAdd.Add(model);
                                continue;
                            }
                            else
                            {

                            }
                        }
                    }



                    //engineDataRelExcept.Add(model);
                }
                //engineDataRelDel = engineDataRel.Except(engineDataRelExcept).ToList();
                List<string> delEngineDataRelIDs = new List<string>(); //engineDataRelDel.Select(x => x.EngineDataRelID).ToList();
                ec_enginedata_relService.SaveEntity(ProjectId, engineDataRelAdd, delEngineDataRelIDs);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        /// <summary>
        /// 对应设备 - 电缆（电缆的起始设备，IsEnd1）
        /// </summary>
        /// <param name="ProjectId"></param>
        /// <param name="RelTypeID"></param>
        /// <param name="RelEngineData1IDs"></param>
        /// <param name="relEngineData2ID">电缆ID，大概率</param>
        /// <param name="NeedRemove"></param>
        public void SaveEntitys(string ProjectId, string RelTypeID, List<string> RelEngineData1IDs, string relEngineData2ID, bool NeedRemove = false)
        {
            try
            {

                //获取当前工程数据ID关联的数据(不管在end1 还是 end2）
                var engineDataRel = GetList("{ProjectId:\"" + ProjectId + "\",RelTypeID:\"" + RelTypeID + "\",RelEngineDataID:\"" + relEngineData2ID + "\"}").ToList();
                ec_enginedata_relEntity model = new ec_enginedata_relEntity();
                List<ec_enginedata_relEntity> engineDataRelAdd = new List<ec_enginedata_relEntity>();
                //List<ec_enginedata_relEntity> engineDataRelDel = new List<ec_enginedata_relEntity>();
                //List<ec_enginedata_relEntity> engineDataRelExcept = new List<ec_enginedata_relEntity>();//用来比较集合之间的差集
                foreach (var item in RelEngineData1IDs)
                {
                    if (NeedRemove)
                    {
                        this.DeleteEntity(ProjectId, RelTypeID, "", relEngineData2ID);
                        model = new ec_enginedata_relEntity();
                        model.Create();
                        model.RelTypeID = RelTypeID;
                        model.RelEngineData1ID = item;
                        model.RelEngineData2ID = relEngineData2ID;
                        engineDataRelAdd.Add(model);
                        continue;
                    }
                    else
                    {
                        //先判断位号之间是否有关联关系 关联关系不存在就新增 存在就不用管
                        model = engineDataRel?.Find(x => x.RelEngineData1ID == item && x.RelEngineData2ID == relEngineData2ID);
                        if (model == null)
                        {
                            model = engineDataRel?.Find(x => x.RelEngineData2ID == item && x.RelEngineData1ID == relEngineData2ID);
                            //反过来如果连接关系有，那也不会新建
                            if (model == null)
                            {
                                model = new ec_enginedata_relEntity();
                                model.Create();
                                model.RelTypeID = RelTypeID;
                                model.RelEngineData1ID = item;
                                model.RelEngineData2ID = relEngineData2ID;
                                engineDataRelAdd.Add(model);
                                continue;
                            }
                            else
                            {

                            }
                        }
                    }



                    //engineDataRelExcept.Add(model);
                }
                //engineDataRelDel = engineDataRel.Except(engineDataRelExcept).ToList();
                List<string> delEngineDataRelIDs = new List<string>(); //engineDataRelDel.Select(x => x.EngineDataRelID).ToList();
                ec_enginedata_relService.SaveEntity(ProjectId, engineDataRelAdd, delEngineDataRelIDs);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        #endregion

    }
}
